package net.roobook.cms.common.web;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Roobook
 * @email 327878610@qq.com
 * @link https://roobook.net
 * @Description controller基类，实现将JSON格式结果的输出方法
 * @date 2023/9/7 16:00
 **/
public class BaseController {
    public Logger logger = LoggerFactory.getLogger(getClass());

    protected HttpServletRequest request;
    protected HttpServletResponse response;

    protected HttpSession session;
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }

    /**
     * 转换字符串为json 格式
     * @param str 普通字符串
     */
    public void outJson(Object obj) {
        getResponse().setContentType("text/html;charset=UTF-8");
        outJsonString(JSONObject.toJSONString(obj, SerializerFeature.WriteMapNullValue));
    }

    /**
     * 转换字符串为json 格式
     * @param str 普通字符串
     */
    public void outJsonString(String str) {
        getResponse().setContentType("text/html;charset=UTF-8");
        outString(str);
    }



    /**
     * 输出字符串到页面
     * @param str 字符
     */
    public void outString(String str) {
        try {
            getResponse().setHeader("Cache-Control", "no-cache");
            getResponse().setHeader("Cache-Control", "no-store");
            getResponse().setDateHeader("Expires", 0L);
            getResponse().setHeader("Pragma", "no-cache");
            PrintWriter out = getResponse().getWriter();
            out.write(str);
            getResponse().flushBuffer();
        } catch (IOException e) {
        }
    }
    /**
     * 取得Request对象
     * @return HttpServletRequest对象
     */
    public HttpServletRequest getRequest() {
        return request;
    }

    /**
     * 取得Response对象
     * @return HttpServletResponse对象
     */
    public HttpServletResponse getResponse() {
        return response;
    }


    public String getUserId(){
        return (String) StpUtil.getLoginId();
    }

}
